package com.example.my_music_palyer.controller;

import com.example.my_music_palyer.model.User;
import com.example.my_music_palyer.service.ImageService;
import com.example.my_music_palyer.service.UserService;
import com.example.my_music_palyer.common.tools.Constant;
import com.example.my_music_palyer.common.tools.ResponseBodyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RequestMapping("/user")
@RestController
@ResponseBody
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private ImageService imageService;


    @RequestMapping("/login")
    public ResponseBodyMessage<User> login(String username, String password, HttpServletRequest req) {
        System.out.println("=== 登录请求 ===");
        System.out.println("用户名: " + username);
        System.out.println("密码: " + password);
        
        // 参数验证
        if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) {
            System.out.println("用户名或密码为空");
            return new ResponseBodyMessage<>(-1, "用户名或密码不能为空", null);
        }
        
        // 查询用户
        User user = userService.selectByUserName(username);
        if (user == null) {
            System.out.println("用户不存在: " + username);
            User failUser = new User();
            failUser.setId(-1);
            failUser.setUsername(username);
            failUser.setPassword("");
            return new ResponseBodyMessage<>(-1, "用户不存在!", failUser);
        }
        
        System.out.println("用户存在，ID: " + user.getId() + ", 角色: " + user.getRole());
        System.out.println("数据库中的密码哈希: " + user.getPassword());
        
        // 验证密码
        boolean passwordValid = bCryptPasswordEncoder.matches(password, user.getPassword());
        System.out.println("密码验证结果: " + passwordValid);
        
        if (!passwordValid) {
            System.out.println("密码验证失败");
            user.setPassword("");
            return new ResponseBodyMessage<>(-1, "密码或用户名错误", user);
        }
        
        System.out.println("密码验证成功，开始设置session");
        
        // 密码验证成功，设置session
        try {
            // 清除密码信息
            user.setPassword("");
            
            // 设置session
            HttpSession session = req.getSession(true);
            session.setAttribute(Constant.USERINFO_SESSION_KEY, user);
            session.setAttribute("user", user);
            
            System.out.println("Session设置成功，用户ID: " + user.getId());
            
            return new ResponseBodyMessage<>(200, "登陆成功!", user);
        } catch (Exception e) {
            System.out.println("设置session时发生错误: " + e.getMessage());
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1, "登录过程中发生错误", null);
        }
    }

    @RequestMapping("/register")
    ResponseBodyMessage<User> register(String username, String password) {
        User user1 = userService.selectByUserName(username);
        if (user1 != null) {
            //用户名已经被注册
            user1.setPassword("");
            return new ResponseBodyMessage<>(-1, "用户名已被注册", user1);
        }

        //注册此用户名
        User user = new User();
        user.setUsername(username);
        user.setRole("user"); // 设置默认角色为普通用户

        //加密并且注册到数据库中
        user.setPassword(bCryptPasswordEncoder.encode(password));
        int flg = userService.registerUser(user);
        if (flg == 1) {
            System.out.println("用户注册成功!");
            user.setPassword("");

            //设置用户初始图像
            User initUser = userService.selectByUserName(username);
            imageService.uploadImage("1.jpg", initUser);

            return new ResponseBodyMessage<>(200, "用户注册成功", user);
        } else {
            User failUser = new User();
            failUser.setUsername(username);
            return new ResponseBodyMessage<>(-1, "内部错误请联系管理员", failUser);
        }


    }

    @RequestMapping("/getCurrentUser")
    public ResponseBodyMessage<User> getCurrentUser(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            return new ResponseBodyMessage<>(-1, "用户未登录", null);
        }
        
        User user = (User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        user.setPassword(""); // 不返回密码
        return new ResponseBodyMessage<>(200, "获取用户信息成功", user);
    }

    @RequestMapping("/out")
     void out(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession(false);
        if (session != null) {
            User loginUser = (User) session.getAttribute("user");
            if (loginUser != null) {
                System.out.println(loginUser.getUsername()+" 退出！！！！！！！！！");
            }
            session.invalidate();
        }
        resp.sendRedirect("/login.html");
    }

    /**
     * 获取用户详细信息（用于profile页面）
     */
    @RequestMapping("/getProfile")
    public ResponseBodyMessage<User> getProfile(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            return new ResponseBodyMessage<>(-1, "用户未登录", null);
        }
        
        User sessionUser = (User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        // 从数据库重新获取完整的用户信息
        User fullUser = userService.selectByUserName(sessionUser.getUsername());
        if (fullUser != null) {
            fullUser.setPassword(""); // 不返回密码
        }
        
        return new ResponseBodyMessage<>(200, "获取用户信息成功", fullUser);
    }

    /**
     * 更新用户个人信息
     */
    @RequestMapping("/updateProfile")
    public ResponseBodyMessage<User> updateProfile(String nickname, HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            return new ResponseBodyMessage<>(-1, "用户未登录", null);
        }
        
        User sessionUser = (User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        
        // 检查是否为管理员
        if ("admin".equals(sessionUser.getRole())) {
            return new ResponseBodyMessage<>(-1, "管理员账户不允许修改个人信息", null);
        }
        
        // 参数验证
        if (nickname == null || nickname.trim().isEmpty()) {
            return new ResponseBodyMessage<>(-1, "昵称不能为空", null);
        }
        
        if (nickname.length() > 50) {
            return new ResponseBodyMessage<>(-1, "昵称长度不能超过50个字符", null);
        }
        
        try {
            // 创建更新对象
            User updateUser = new User();
            updateUser.setId(sessionUser.getId());
            updateUser.setNickname(nickname.trim());
            
            int result = userService.updateUserProfile(updateUser);
            if (result > 0) {
                // 更新session中的用户信息
                sessionUser.setNickname(nickname.trim());
                session.setAttribute(Constant.USERINFO_SESSION_KEY, sessionUser);
                
                return new ResponseBodyMessage<>(200, "个人信息更新成功", sessionUser);
            } else {
                return new ResponseBodyMessage<>(-1, "更新失败，请稍后重试", null);
            }
        } catch (Exception e) {
            System.out.println("更新用户信息时发生错误: " + e.getMessage());
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1, "更新过程中发生错误", null);
        }
    }

    /**
     * 上传用户头像
     */
    @RequestMapping("/uploadAvatar")
    public ResponseBodyMessage<String> uploadAvatar(@RequestParam("avatar") MultipartFile file, HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            return new ResponseBodyMessage<>(-1, "用户未登录", null);
        }
        
        User sessionUser = (User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        
        // 检查是否为管理员
        if ("admin".equals(sessionUser.getRole())) {
            return new ResponseBodyMessage<>(-1, "管理员账户不允许修改头像", null);
        }
        
        // 检查文件
        if (file == null || file.isEmpty()) {
            return new ResponseBodyMessage<>(-1, "请选择要上传的头像文件", null);
        }
        
        // 验证文件类型
        if (!file.getContentType().startsWith("image/")) {
            return new ResponseBodyMessage<>(-1, "请选择图片文件", null);
        }
        
        // 验证文件大小 (5MB)
        if (file.getSize() > 5 * 1024 * 1024) {
            return new ResponseBodyMessage<>(-1, "图片大小不能超过5MB", null);
        }
        
        try {
            // 生成唯一的头像文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String avatarFileName = "avatar_" + sessionUser.getId() + "_" + System.currentTimeMillis() + extension;
            
            // 使用现有的图片上传服务
            int imageResult = imageService.uploadImage(avatarFileName, sessionUser);
            if (imageResult > 0) {
                // 更新user表中的头像路径
                String avatarPath = "/image/" + avatarFileName;
                int userResult = userService.updateUserAvatar(sessionUser.getId(), avatarPath);
                if (userResult > 0) {
                    // 更新session中的用户信息
                    sessionUser.setAvatar(avatarPath);
                    session.setAttribute(Constant.USERINFO_SESSION_KEY, sessionUser);
                    
                    return new ResponseBodyMessage<>(200, "头像上传成功", avatarPath);
                } else {
                    return new ResponseBodyMessage<>(-1, "头像信息保存失败", null);
                }
            } else {
                return new ResponseBodyMessage<>(-1, "头像上传失败", null);
            }
        } catch (Exception e) {
            System.out.println("上传头像时发生错误: " + e.getMessage());
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1, "头像上传过程中发生错误", null);
        }
    }


}




